from fastapi import APIRouter
from app.funcs import gen_a
from app.module.entity.vo.task_state_vo import TaskStatusModel
from utils.tools import logger
from utils.response_util import response_200, response_500
from funboost import AsyncResult, HasNotAsyncResult
from app.client.BotClient import KnowledgeBaseClient

genQaController = APIRouter()


@genQaController.post("/push_q", summary="选择知识库，提交问题")
async def gen_qa(question: str, knowledge_name: str):
    async_result = gen_a.push(question, knowledge_name)
    logger.debug(f"返回taskid给前端： [{async_result.task_id}]")
    model = TaskStatusModel(task_id=async_result.task_id)
    return response_200(data=model, message="提交成功")


@genQaController.get("/get_a/{taskid:str}", summary="获取问题答案")
async def get_qa_result(taskid: str):
    """前端每隔3秒轮训ajax，个人建议可以考虑尝试函数里面得到结果后发布到mqtt topic，前端订阅这个topic，mqtt比ajax和websocket都好用
    如果前端不需要关注结果，不需要调用此接口
    """
    try:
        data = AsyncResult(task_id=taskid, timeout=1).get()
        return response_200(data=data, message="查询成功")
    except HasNotAsyncResult:
        logger.warning(f"taskid [ {taskid} ] 还没执行完成或者taskid错误")
        return response_500(
            message="taskid [ " + taskid + " ] 还没执行完成或者taskid错误"
        )


@genQaController.get("/knowledge/list", summary="知识库列表")
async def get_knowledge_list():

    response = KnowledgeBaseClient().get_knowledge_base()
    return response_200(data=response["data"])
